package com.borqsprocessmanager.activity;

import com.borqsprocessmanager.App;
import com.borqsprocessmanager.BatteryManagerService;
import com.borqsprocessmanager.ConfigParams;
import com.borqsprocessmanager.Constant;
import com.borqsprocessmanager.IService;
import com.borqsprocessmanager.IsRootThread;
import com.borqsprocessmanager.MainActivity;
import com.borqsprocessmanager.R;
import com.borqsprocessmanager.fragments.BaseFragment;
import com.borqsprocessmanager.fragments.NetWorkFrament;
import com.borqsprocessmanager.fragments.ProcessManagerFragment;
import com.borqsprocessmanager.fragments.ResultFragment;
import com.borqsprocessmanager.fragments.WhiteFragment;
import com.borqsprocessmanager.info.ActionMapInfo;
import com.borqsprocessmanager.info.WhiteMapMapInfo;
import com.borqsprocessmanager.util.Log;
import com.borqsprocessmanager.util.PreferencesUtil;
import com.borqsprocessmanager.view.MessagePopWindow;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.NotificationType;
import com.umeng.fb.UMFeedbackService;
import com.umeng.update.UmengUpdateAgent;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ActionBar.OnNavigationListener;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.SpinnerAdapter;
import android.widget.Toast;

public class MainActivity2 extends Activity implements OnNavigationListener,
        ServiceConnection {

    private final String TAG = "MainActivity";
    public final static String BUNDLE_KEY = "MainActivity_bundle_Key";
    public final static int TYPE_FADE = 0;
    public final static int TYPE_SLIDE_LEFT = 1;

    public static int simpleId = 0;
    public static boolean isRoot = false;

    // public BatteryManagerService mService;
    public BaseFragment mProcessManagerFragment, mResultFragment,
            mNetWorkFrament, mWhiteFragment;

    public ActionMapInfo actionMap;
    public WhiteMapMapInfo whiteMap;

    public String[] fragmentTags;

    private IService personService;
    private Handler mHandler;
    private boolean isMainFragment = true;
    private long exitTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUmeng();
        ConfigParams.updataConfig(App.mContext);

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                isRoot = msg.getData().getBoolean(BUNDLE_KEY);
                finalView();
                startBatteryManagerService();
                initData();
                setListener();
                if (isRoot) {
                    com.borqsprocessmanager.util.Log.v(TAG, "root");
                    initActionBar();
                } else {
                    com.borqsprocessmanager.util.Log.v(TAG, "no_root");
                    addFragment(fragmentTags[0], TYPE_FADE, false);
                    Toast.makeText(MainActivity2.this,
                            getString(R.string.root_toast), Toast.LENGTH_LONG)
                            .show();
                }
            }
        };
        new IsRootThread(mHandler).start();
        Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                showMessageDialog();
            }
        };
        handler.sendEmptyMessageDelayed(0, 2000);
        com.borqsprocessmanager.util.Log.v(TAG, "onCreate");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.v(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        Log.v(TAG, "onResume");
        super.onResume();
    }

    public void onPause() {
        super.onPause();
        Log.v(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.v(TAG, "onStop");
        try {
            personService.setActionMap(actionMap);
            personService.setWhiteMap(whiteMap);
            personService.setSimpleId(simpleId);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        try {
            Log.v(TAG, "unbindService");
            unbindService(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private void initUmeng() {
        UMFeedbackService.enableNewReplyNotification(App.mContext,
                NotificationType.AlertDialog);
        MobclickAgent.updateOnlineConfig(App.mContext);
        UmengUpdateAgent.update(App.mContext);
    }

    private void initData() {
        // type_res_fragment = (getResources()
        // .getStringArray(R.array.action_list_newdata_root))[0]
        // .toString();
        // type_process_fragment = (getResources()
        // .getStringArray(R.array.action_list_newdata_root))[1]
        // .toString();
        // type_network_fragment = (getResources()
        // .getStringArray(R.array.action_list_newdata_root))[2]
        // .toString();

        // type_process_fragment;
        // type_res_fragment;
        // type_network_fragment;
        fragmentTags = getResources().getStringArray(
                R.array.action_list_fragment);
    }

    private void finalView() {
        mProcessManagerFragment = new ProcessManagerFragment();
        mResultFragment = new ResultFragment();
        mNetWorkFrament = new NetWorkFrament();
        mWhiteFragment = new WhiteFragment();

        Log.v(TAG, "finalView");
    }

    private void initActionBar() {
        SpinnerAdapter mSpinnerAdapter = null;
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        // if (isNewData) {
        mSpinnerAdapter = ArrayAdapter.createFromResource(this,
                R.array.action_list_newdata_root, R.layout.action_bar_item);
        // } else {
        // mSpinnerAdapter = ArrayAdapter.createFromResource(this,
        // R.array.action_list_root, R.layout.action_bar_item);
        // tabStrs = getResources().getStringArray(R.array.action_list_root);
        // }
        actionBar.setListNavigationCallbacks(mSpinnerAdapter, this);
        actionBar.setBackgroundDrawable(getResources().getDrawable(
                R.color.write_title));
    }

    private void setListener() {
        Log.v(TAG, "setListener");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, App.mContext.getText(R.string.about));
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 0:
            new MessagePopWindow().showMessagePop(this);
            ConfigParams.setIsNewMessage(0);
            return true;
        }
        return false;
    }

    private void startBatteryManagerService() {
        Intent intent = new Intent(this, BatteryManagerService.class);
        startService(intent);
        bindService(intent, this, Context.BIND_AUTO_CREATE);
    }

    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        // Fragment newFragment = null;
        String tag = fragmentTags[itemPosition];
        Log.v(TAG, "tag.equals===" + tag);
        // if (tag.equals(tabStrs[0])) {
        // addFragment(tag, false);
        // // newFragment = mResultFragment;
        // } else if (tag.equals(tabStrs[1])) {
        // addFragment(tag, false);
        // // newFragment = mProcessManagerFragment;
        //
        // } else if (tag.equals(tabStrs[2])) {
        // // newFragment = mNetWorkFrament;
        // addFragment(tag, false);
        // }
        addFragment(tag, TYPE_FADE, false);
        // FragmentTransaction ft = getFragmentManager().beginTransaction();
        // ft.replace(R.id.main_layout, newFragment, tag);
        // ft.commit();
        return true;
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        personService = IService.Stub.asInterface(service);
        try {
            actionMap = personService.getActionMap();
            whiteMap = personService.getWhiteMap();
            // int simpleId = personService.getSimpleId();
            setFragmentService(personService, actionMap, whiteMap);
            Log.v(TAG, "onServiceConnected");
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void setFragmentService(IService personService,
            ActionMapInfo acitonMapInfo, WhiteMapMapInfo whiteMapInfo) {
        mProcessManagerFragment.onBindServiced(personService,
                acitonMapInfo.actionMap, whiteMapInfo.whiteMap);
        mResultFragment.onBindServiced(personService, acitonMapInfo.actionMap,
                whiteMapInfo.whiteMap);
        mNetWorkFrament.onBindServiced(personService, acitonMapInfo.actionMap,
                whiteMapInfo.whiteMap);
        mWhiteFragment.onBindServiced(personService, acitonMapInfo.actionMap,
                whiteMapInfo.whiteMap);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    @Override
    public void onBackPressed() {
        try {
            if (isMainFragment) {
                exitApp(this);
            } else {
                super.onBackPressed();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addFragment(String tag, int animType, boolean isAddBackStack) {
        Fragment newFragment = null;
        if (tag.equals(fragmentTags[0])) {
            newFragment = mResultFragment;
            isMainFragment = true;
        } else if (tag.equals(fragmentTags[1])) {
            newFragment = mProcessManagerFragment;
            isMainFragment = true;
        } else if (tag.equals(fragmentTags[2])) {
            newFragment = mNetWorkFrament;
            isMainFragment = true;
        } else if (tag.equals(fragmentTags[3])) {
            newFragment = mWhiteFragment;
            isMainFragment = false;
        }
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        if (isAddBackStack) {
            ft.addToBackStack(null);
        }
        setFragmentAnimation(ft, animType);

        ft.replace(R.id.main_layout, newFragment, tag);
        ft.commit();
    }

    private void setFragmentAnimation(FragmentTransaction ft, int type) {
        switch (type) {
        case TYPE_FADE:
            ft.setCustomAnimations(android.R.animator.fade_in,
                    android.R.animator.fade_out);
            break;
        case TYPE_SLIDE_LEFT:
            ft.setCustomAnimations(R.anim.fragmentanim_in, R.anim.fragmentanim,
                    R.anim.fragmentanim_pop_cur, R.anim.fragmentanim_pop_pre);
            break;
        default:
            break;
        }
    }

    public void exitApp(Activity activity) {
        if ((System.currentTimeMillis() - exitTime) > 1500) {
            Toast.makeText(this, getString(R.string.exit), Toast.LENGTH_SHORT)
                    .show();
            exitTime = System.currentTimeMillis();
        } else {
            this.finish();
            Handler handler = new Handler() {
                public void handleMessage(Message msg) {
                    System.exit(0);
                }
            };
            handler.sendEmptyMessageDelayed(0, 1000);
        }
    }

    private void showMessageDialog() {
        if (ConfigParams.IS_NEW_MESSAGE == 1) {
            new MessagePopWindow().showMessagePop(this);
            ConfigParams.setIsNewMessage(0);
        }
    }

    public boolean isNewData() {
        return PreferencesUtil.getInstance(App.mContext).getBoolean(
                Constant.KEY_IS_NEWDATA);
    }

}
